package com.gym.core.serialize;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class Serialize {
	private static final Logger log = LoggerFactory.getLogger(Serialize.class);
	
	public static Object ByteToObject(byte[] bytes) {
	     if(null == bytes || 0 == bytes.length) {
	    	 return null;
	     }
	     
		Object obj = null;
		ObjectInputStream oi = null;
		
		try {
    		//bytearray to object
			ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
    		oi = new ObjectInputStream(bi);
    
    		obj = oi.readObject();
    
		}catch(Exception e){
			System.out.println(e);
		    log.error("error in Serialize ByteToObject:"+e.getMessage(), e);
		}finally{
			if(null != oi){
				try {
					oi.close();
				} catch (Exception e2) {
				}
			}
		}
		return obj;
	}
	
	public static byte[] ObjectToByte(Object obj) {
		byte[] bytes = null;
		ObjectOutputStream oo = null;
		try  {
		    //object to bytearray
		    ByteArrayOutputStream bo = new ByteArrayOutputStream();
		    oo = new ObjectOutputStream(bo);
		    oo.writeObject(obj);

		    bytes = bo.toByteArray();
		}catch(Exception e){
			System.out.println(e);
		    log.error("error in Serialize ObjectToByte:"+e.getMessage(), e);
		}finally{
			if(null != oo){
				try {
					oo.close();
				} catch (Exception e2) {
				}
			}
		}
		
		return bytes;
	}
}
